package com.hyt.it.ogt.controller.ykcj.analysis;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Collections;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.hyt.common.apiInfor.DataType;
import com.hyt.common.apiInfor.ParamType;
import com.hyt.it.ogt.controller.base.BaseController;
import com.hyt.it.ogt.ykcj.common.core.domain.AjaxResult;
import com.hyt.it.ogt.ykcj.common.core.page.TableDataInfo;
import com.hyt.it.ogt.ykcj.common.enums.CommonEnums;
import com.hyt.it.ogt.ykcj.common.exception.CustomException;
import com.hyt.it.ogt.ykcj.domain.vo.analysis.AnalysisVo;
import com.hyt.it.ogt.ykcj.domain.vo.analysis.BlockAllAnalysisVo;
import com.hyt.it.ogt.ykcj.domain.vo.analysis.CheckExamSubjectVo;
import com.hyt.it.ogt.ykcj.domain.vo.analysis.ExamScoreAnalysisVo;
import com.hyt.it.ogt.ykcj.service.analysis.IEnterpriseExamineeAnalysisDataService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperationSort;
import io.swagger.annotations.ApiSort;

/**
 * description
 *
 * @author yaojian
 * @createTime 2021/12/31
 */
@Api(tags = "ScoreAnalysis.16.成绩分析", value = "成绩分析")
@ApiSort(value = 211)
@RestController
@RequestMapping("/score/analysis")
public class EnterpriseExamineeAnalysisDataController extends BaseController {

    @Autowired
    private IEnterpriseExamineeAnalysisDataService enterpriseExamineeAnalysisDataService;


    /**
     * 检查考试下是否设置科目
     */
    @ApiOperation(value = "检查考试下是否设置科目", notes = "（传examId）")
    @GetMapping(value = "checkExam/{examId}")
    @ApiOperationSort(5)
    public AjaxResult checkExamSubject(@PathVariable String examId) {
        if (StringUtils.isEmpty(examId)) {
            throw new CustomException("考试id不能为空！");
        }
        CheckExamSubjectVo checkExamSubjectVo = enterpriseExamineeAnalysisDataService.checkExamSubject(examId);
        return AjaxResult.success(checkExamSubjectVo);
    }

    /**
     * 获取考试成绩分析信息
     */
    @ApiOperation("获取考试总的分析信息统计")
    @PostMapping(value = "/")
    @ApiOperationSort(10)
    public AjaxResult getExamAnalysisData( @RequestBody AnalysisVo analysisVo) {
        ExamScoreAnalysisVo examScoreAnalysisVo = enterpriseExamineeAnalysisDataService.selectTotalAnalysisById(analysisVo);
        return AjaxResult.success(examScoreAnalysisVo);
    }

    /**
     * 获取考试成绩分析列表信息
     */
    @ApiOperation("获取考试成绩分析列表信息")
    @PostMapping(value = "/list")
    @ApiOperationSort(20)
    public TableDataInfo getListAnalysisData(@RequestBody AnalysisVo analysisVo) {
        if (CommonEnums.ANALYSIS_TYPE_SBUJECT.getCode().equals(analysisVo.getType())) {
            return enterpriseExamineeAnalysisDataService.selectSubjectAnalysisList(analysisVo) ;
        } else if (CommonEnums.ANALYSIS_TYPE_SEX.getCode().equals(analysisVo.getType())
                || CommonEnums.ANALYSIS_TYPE_EDUCATION.getCode().equals(analysisVo.getType())
                || CommonEnums.ANALYSIS_TYPE_PROVINCE.getCode().equals(analysisVo.getType())
                || CommonEnums.ANALYSIS_TYPE_CITY.getCode().equals(analysisVo.getType())
                || CommonEnums.ANALYSIS_TYPE_EXAMROOM.getCode().equals(analysisVo.getType())
                || CommonEnums.ANALYSIS_TYPE_EXAM.getCode().equals(analysisVo.getType())
        ) {
            return  enterpriseExamineeAnalysisDataService.selectBaseAnalysisList(analysisVo);
        }
        return getDataTable(Collections.EMPTY_LIST);
    }

    /**
     * 获取分段统计数据
     */
    @ApiOperation("获取分段统计数据")

    @PostMapping(value = "/block")
    @ApiOperationSort(30)
    public AjaxResult getBlockListAnalysisData( @RequestBody AnalysisVo analysisVo) {
        //根据不同类型调用service
        BlockAllAnalysisVo blockAllAnalysisVo = null;
        if (CommonEnums.ANALYSIS_TYPE_SBUJECT.getCode().equals(analysisVo.getType())) {
            blockAllAnalysisVo = enterpriseExamineeAnalysisDataService.selectBlockSubjectAnalysisList(analysisVo);
        } else if (CommonEnums.ANALYSIS_TYPE_SEX.getCode().equals(analysisVo.getType())
                || CommonEnums.ANALYSIS_TYPE_EDUCATION.getCode().equals(analysisVo.getType())
                || CommonEnums.ANALYSIS_TYPE_PROVINCE.getCode().equals(analysisVo.getType())
                || CommonEnums.ANALYSIS_TYPE_CITY.getCode().equals(analysisVo.getType())
                || CommonEnums.ANALYSIS_TYPE_EXAMROOM.getCode().equals(analysisVo.getType())
                || CommonEnums.ANALYSIS_TYPE_EXAM.getCode().equals(analysisVo.getType())
        ) {
            blockAllAnalysisVo = enterpriseExamineeAnalysisDataService.selectBlockAnalysisList(analysisVo);
        }
        return AjaxResult.success(blockAllAnalysisVo);
    }

    /**
     * 导出成绩分析数据列表
     */
    @ApiOperation(value = "导出数据", notes = "（没有对应文件响应为空")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examId", value = "考试ID", dataType = DataType.STRING, paramType = ParamType.QUERY, required = true),
            @ApiImplicitParam(name = "subjectId", value = "科目id", dataType = DataType.STRING, paramType = ParamType.QUERY, required = true),
            @ApiImplicitParam(name = "pageNum", value = "页面", dataType = DataType.STRING, paramType = ParamType.QUERY, required = true),
            @ApiImplicitParam(name = "pageSize", value = "页大小", dataType = DataType.STRING, paramType = ParamType.QUERY, required = true),
            @ApiImplicitParam(name = "orderByColumn", value = "排序字段", dataType = DataType.STRING, paramType = ParamType.QUERY, required = false),
            @ApiImplicitParam(name = "orderBy", value = "排序(排序(ascending，descending))", dataType = DataType.STRING, paramType = ParamType.QUERY, required = false)
    })
    @GetMapping(value = "export")
    @ApiOperationSort(40)
    public void exportSubject(@Validated AnalysisVo analysisVo, HttpServletResponse response) {

        XSSFWorkbook wb = enterpriseExamineeAnalysisDataService.exportAnalysisList(analysisVo, null);
        if(null == wb){
            throw new CustomException("没有需要导出的数据");
        }
        OutputStream fos = null;
        try {
            response.setContentType("octets/stream");
            response.setContentType("application/octet-stream;charset=utf-8");
            if (CommonEnums.ANALYSIS_TYPE_SBUJECT.getCode().equals(analysisVo.getType())) {
                response.setHeader("Content-Disposition", "attachment;filename="
                        + new String(CommonEnums.EXPORT_SUBJECT_ANALYSIS_FILE_NAME.getDesc().getBytes("gb2312"), "ISO8859-1") + ".xlsx");
            } else if (CommonEnums.ANALYSIS_TYPE_SEX.getCode().equals(analysisVo.getType())) {
                response.setHeader("Content-Disposition", "attachment;filename="
                        + new String(CommonEnums.EXPORT_SEX_ANALYSIS_FILE_NAME.getDesc().getBytes("gb2312"), "ISO8859-1") + ".xlsx");
            } else if (CommonEnums.ANALYSIS_TYPE_EDUCATION.getCode().equals(analysisVo.getType())) {
                response.setHeader("Content-Disposition", "attachment;filename="
                        + new String(CommonEnums.EXPORT_EDUCATION_ANALYSIS_FILE_NAME.getDesc().getBytes("gb2312"), "ISO8859-1") + ".xlsx");
            } else if (CommonEnums.ANALYSIS_TYPE_PROVINCE.getCode().equals(analysisVo.getType())) {
                response.setHeader("Content-Disposition", "attachment;filename="
                        + new String(CommonEnums.EXPORT_PROVINCE_ANALYSIS_FILE_NAME.getDesc().getBytes("gb2312"), "ISO8859-1") + ".xlsx");
            } else if (CommonEnums.ANALYSIS_TYPE_CITY.getCode().equals(analysisVo.getType())) {
                response.setHeader("Content-Disposition", "attachment;filename="
                        + new String(CommonEnums.EXPORT_CITY_ANALYSIS_FILE_NAME.getDesc().getBytes("gb2312"), "ISO8859-1") + ".xlsx");
            }
            else if (CommonEnums.ANALYSIS_TYPE_EXAMROOM.getCode().equals(analysisVo.getType())) {
                response.setHeader("Content-Disposition", "attachment;filename="
                        + new String(CommonEnums.ANALYSIS_TYPE_EXAMROOM.getDesc().getBytes("gb2312"), "ISO8859-1") + ".xlsx");
            }
            else if (CommonEnums.ANALYSIS_TYPE_EXAM.getCode().equals(analysisVo.getType())) {
                response.setHeader("Content-Disposition", "attachment;filename="
                        + new String(CommonEnums.ANALYSIS_TYPE_EXAM.getDesc().getBytes("gb2312"), "ISO8859-1") + ".xlsx");
            }
            fos = response.getOutputStream();
            wb.write(response.getOutputStream());
        } catch (Exception e) {
            logger.error("下载文件失败", e);
        } finally {
            try {
                wb.close();
                if(null != fos){
                    fos.close();
                }

            } catch (IOException e) {
                logger.error("关闭导出文件流异常:{}", e);
            }
        }
    }


}
